#include <highgui.h>
#include <iostream>
#include <cv.h>

#include "resourceTracker.h"
using namespace cv;
using namespace std;

/*
 *  AVITagger.cpp
 *  
 *
 *  Created by Rasmus Kyng on 11/01/2011.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 
 
 Compatibility: Tested on Mac, should run on Windows, may not run on Linux.
 
 Attribution: This uses code bits from the book Learning OpenCV.
 
 LOCV notes:
 
 License:
 Oct. 3, 2008
 Right to use this code in any way you want without warrenty, support or any guarentee of it working.
 
 Learning OpenCV: Computer Vision with the OpenCV Library
 by Gary Bradski and Adrian Kaehler
 Published by O'Reilly Media, October 3, 2008
 *
 */

//Variables

//Horrible dependencies on global variables here! How I wish I could use Java and have nice GC.
Mat frame;
cv::Ptr< cv::VideoCapture > capture;

ResourceTracker* rt;

//Window name for display
char* windowName = "AVI Gesture Tagger";

int main( int argc, char** argv ) {
	
	if (argc != 2) {
		cerr << "Usage: AVIGestureTagger videoName" << endl;
		return -1;
	}
	
	char* inputVideoNameString = argv[1];
	
	namedWindow( windowName, CV_WINDOW_AUTOSIZE );
	
	rt = new ResourceTracker( "../config/runtimeSettings/cfg.xml" );
	rt->loadCategory("TestData");
	//rt->loadCategory("Interannotator");
	
	
	rt->startVideoGestureTagging( inputVideoNameString );
	
	capture = rt->getFileVideoCapture( inputVideoNameString );
	
	*capture >> frame;
	
	if( frame.empty() ) {
		std::cout << "No frames found" << std::endl;
		delete rt;
		return -1;
	}
	
	// -- main gesture tagging loop -- //
	
	bool taggingAborted = false;
	
	while ( !frame.empty() && !taggingAborted ) {
		imshow( windowName, frame ); //show the first frame so user may begin tagging
		
		bool keyRecognised = false;
		
		while ( !keyRecognised ) {
			char c = waitKey(0);
			
			switch (c) {
				case 'o':
					rt->tagVideoHandOpen();
					keyRecognised = true;
					break;
				case 'c':
					rt->tagVideoHandClosed();
					keyRecognised = true;
					break;
				case 27:
					taggingAborted = true;
					keyRecognised = true;
					break;
				default:
					std::cout << "Keyboard input not recognised. Press 'o' to tag hand as open, press 'c' to tag hand as closed." << std::endl;
					break;
			}
		}
		*capture >> frame; //get next frame
	}
	
	if ( !taggingAborted ) {
		std::cout << "No frames left. Press ESC to exit" << std::endl;
		while( true ) {
			char c = waitKey(0);
			if( c == 27 ) break; //exit if user presses escape
		}
	}
	
	rt->stopGestureVideoTagging();
	
	// -- Clean up -- //
	
	delete rt;
	
	return 0;
}